package com.order.manager.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.UserInfo;
import com.order.manager.service.impl.UserInfoServiceImpl;
import com.order.manager.util.UUIDGeneratorUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * UserDetailsService的实现类
 *
 * @author 24862
 */
@Service
@Slf4j
public class AuthUserDetailService implements UserDetailsService {


    @Resource
    UserInfoServiceImpl userInfoService;

    /**
     * 这一层必须采用username+password
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        UserInfo userLoginInfo = userInfoService.getOne(new QueryWrapper<UserInfo>()
                .eq("username", username)
                .eq("state", '1')
                .eq("is_enable", "1")
        );
        if (userLoginInfo == null) {
            throw new UsernameNotFoundException("username password state error");
        }
        UserInfo userExtendDetails = new UserInfo();
        userExtendDetails.setUsername(userLoginInfo.getUsername());
        userExtendDetails.setPassword(userLoginInfo.getPassword());
        userExtendDetails.setRole(userLoginInfo.getRole());//直接用角色来定义权限，权限是特殊的角色
        userExtendDetails.setIsEnable(userLoginInfo.getIsEnable());
        return userExtendDetails;
    }

    /**
     * 这里解决高并发问题。
     * 在之前要进行一次邮箱的注册数量的统计，如果大于某个数量，那么就返回相对应的账号，并决定是否进行删除操作。
     *
     * @param user
     * @return
     */
    public UserInfo insertUser(UserInfo user) {
        try {
            String userId = UUIDGeneratorUtil.generateRandomUUID();
            user.setUserId(userId);
            user.setInputTime(new Date());
            if (userInfoService.save(user)) {
                //在用户表里面初始化用户信息，添加成功，那么返回该用户的信息，否则返空
                return user;
            }
            return null;
        } catch (Exception e) {
            log.info(e.getMessage());
            return null;
        }
    }
}
